package com.jtpay.sdk.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.jtpay.sdk.R;
import com.jtpay.sdk.adapter.ProductTypeAdapter;
import com.jtpay.sdk.base.BaseActivity;
import com.jtpay.sdk.util.AuthUtil;
import com.jtpay.sdk.util.PayUtilHelper;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import apiUtils.apis.GetPayTypesAPI;
import apiUtils.models.OrderModel;
import apiUtils.models.PayInfo;
import apiUtils.models.PayTypeModel;
import appUtils.ToastUtil;
import butterknife.Bind;
import butterknife.OnClick;
import sdk.pay.model.TokenParam;
import sdk.pay.utils.PayMD5Util;

public class ProductActivity extends BaseActivity implements PayUtilHelper.Observer {
    @Bind(R.id.layout_title_textName)
    TextView mTitleTextView;
    @Bind(R.id.appName_TextView)
    TextView mAppNameTextView;
    @Bind(R.id.appId_TextView)
    TextView mAppIdTextView;
    @Bind(R.id.orderNumber_TextView)
    TextView mOrderNumberTextView;
    @Bind(R.id.orderMoney_TextView)
    TextView mOrderMoneyTextView;
    @Bind(R.id.pay_type_RecycleView)
    RecyclerView mPayTypeRecyclerView;
    private OrderModel mOrderModel;
    private ProductTypeAdapter mTypeAdapter = new ProductTypeAdapter();
    private List<PayTypeModel> mPayTypeModels = new ArrayList<>();
    private static final int REQUEST_CODE = 0x1;

    @Override
    protected void initView() {
        mTitleTextView.setText(R.string.payment_product);
        if (mOrderModel != null) {
            mAppNameTextView.append(mOrderModel.getApplicationName());
            mAppIdTextView.append(mOrderModel.getApplicationId());
            mOrderNumberTextView.append(mOrderModel.getOrderNumber());
            mOrderMoneyTextView.append(mOrderModel.getOrderMoney() + "元");
        }
        mPayTypeRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mPayTypeRecyclerView.setAdapter(mTypeAdapter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismisProgress();
        finish();
    }

    @Override
    protected void initData() {
        PayUtilHelper.getInstance().setParams(PayInfo.getInstance().getAppId(), PayInfo.getInstance().getKeyAES(), PayInfo.getInstance().getVectorAES(), PayInfo.getInstance().getPaySystemId().toLowerCase(), PayInfo.getInstance().getAppKey());
        PayUtilHelper.getInstance().attachObserver(this);
        mOrderModel = PayInfo.getInstance().getOrderModel();
        initPayTypedata();
        mTypeAdapter.setData(mPayTypeModels);
    }

    private void initPayTypedata() {
        showProgress(R.string.get_pay_type_loading);
        new GetPayTypesAPI().getPayTypes(PayInfo.getInstance().getAppId(), new GetPayTypesAPI.Listener() {
            @Override
            public void onSuccess(List<PayTypeModel> models) {
                dismisProgress();
                if (models == null || models.isEmpty()) {
                    return;
                }
                mPayTypeModels.clear();
                mPayTypeModels.addAll(models);
                mTypeAdapter.setData(mPayTypeModels);
            }

            @Override
            public void onFailure(int code, String message) {
                dismisProgress();
                ToastUtil.showShort(R.string.get_pay_type_error);
            }
        });
    }

    @Override
    protected int setView() {
        return R.layout.activity_product;
    }

    @OnClick({R.id.layout_title_iv_left, R.id.switch_channel_Button, R.id.immediate_pay_Button, R.id.exit_View})
    void buttonClick(View v) {
        switch (v.getId()) {
            case R.id.layout_title_iv_left:
                backAction();
                break;
            case R.id.switch_channel_Button:
                switchChannelAction();
                break;
            case R.id.immediate_pay_Button:
                payAction();
                break;
            case R.id.exit_View:
                AuthUtil.getInstance().logOut();
                break;
            default:

                break;
        }
    }

    private void backAction() {
        finish();
    }

    private void switchChannelAction() {
        PayTypeModel model = mTypeAdapter.getSelecteData();
        if (model == null) {
            ToastUtil.showShort(R.string.please_select_payment_product);
            return;
        }
        Intent intent = new Intent(this, SwitchChannelActivity.class);
        intent.putExtra("data", model);
        intent.putExtra("oreder", mOrderModel);
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE:
                    initPayTypedata();
                    break;
                default:

                    break;
            }
        }
    }

    private void payAction() {
        PayTypeModel model = mTypeAdapter.getSelecteData();
        if (model == null) {
            ToastUtil.showShort(R.string.please_select_payment_product);
            return;
        }
        PayInfo.getInstance().setPayTypeName(model.getProductTypeName());
        PayInfo.getInstance().setChannelName(model.getUsingChannelName());
        showProgress(R.string.loading);
        PayUtilHelper.getInstance().pay(model.getProductTypeCode(), getTokenParam(model.getProductTypeCode()));
    }

    @Override
    public void onChangeCallBack() {
        dismisProgress();
    }

    private TokenParam getTokenParam(String code) {
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String app_key = PayInfo.getInstance().getAppKey();
        String p1_appid = PayInfo.getInstance().getAppId();
        String p2_order = mOrderModel.getOrderNumber();
        String p3_money = mOrderModel.getOrderMoney();
        String p6_ordertime = dateFormat.format(date);
        String p8_sign = PayMD5Util.getMD5(
                p1_appid + "&" + p2_order + "&" + p3_money + "&"
                        + p6_ordertime + "&" + code + "&" + app_key);
        TokenParam tokenParam = new TokenParam();
        tokenParam.setP1_appid(p1_appid);
        tokenParam.setP2_orderNumber(p2_order);
        tokenParam.setP3_money(p3_money);
        tokenParam.setP6_orderTime(p6_ordertime);
        tokenParam.setP8_sign(p8_sign);
        return tokenParam;
    }
}
